package cn.jdx.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/*
【测试】:文件上传
 */
@RestController
public class MyFileUploadController {
    @RequestMapping("/upload")
    public String uploadFile2(@RequestParam(name = "file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        System.out.println("[控制器]:文件上传");
        //[1]上传路径保存设置
        String realPath = request.getServletContext().getRealPath("/upload");
        //如果路径不存在则创建
        File uploadedFile = new File(realPath);
        if (!uploadedFile.exists()){
            uploadedFile.mkdir();//创建文件夹
        }
        System.out.println("[保存地址]:"+realPath);
        //直接上传
        file.transferTo(new File(realPath,file.getOriginalFilename()));
        return "ok";
    }
}
